package echat.future.cn.echat.my;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;

import java.util.ArrayList;
import java.util.List;

import echat.future.cn.echat.R;
import echat.future.cn.echat.databinding.FragmentMyBinding;
import echat.future.cn.echat.home.AnchorHomeActivity;
import echat.future.cn.echat.home.ChatActivity;
import echat.future.cn.echat.my.adapter.MeJumpAdapter;
import echat.future.cn.echat.my.adapter.MyJumpDecoration;
import echat.future.cn.echat.my.api.UserApi;
import echat.future.cn.echat.my.bean.AuthUserBean;
import echat.future.cn.echat.my.bean.MeJumpBean;
import echat.future.cn.echat.my.bean.Token;
import echat.future.cn.echat.my.bean.UserBean;
import echat.future.cn.echat.my.bean.UserStatus;
import echat.future.cn.echat.my.form.SendStatusForm;
import echat.future.cn.echat.my.utils.Contancts;
import echat.future.cn.echat.my.utils.HttpUtilsRequst;
import echat.future.cn.echat.my.utils.ImageLoadUtils;
import echat.future.cn.echat.my.utils.MeHelper;
import echat.future.cn.echat.my.utils.RouterHelper;
import echat.future.cn.echat.my.utils.ToastUtils;
import echat.future.cn.echat.my.utils.UserHelper;
import echat.future.cn.echat.my.view.AuthenticationUserActivity;
import echat.future.cn.echat.my.view.AuthenticationZhuboActivity;
import echat.future.cn.echat.my.view.CollegeActivity;
import echat.future.cn.echat.my.view.LikeActivity;
import echat.future.cn.echat.my.view.MyFanseActivity;
import echat.future.cn.echat.my.view.PersonInfoActivity;
import echat.future.cn.echat.my.view.ValueActivity;
import lumingweihua.future.cn.baselibgxh.base.BaseFragment;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.utils.MD5;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2018/8/9.
 */

public class MyFragment extends BaseFragment {


    FragmentMyBinding binding;

    MeJumpAdapter meJumpAdapter;

    private List<MeJumpBean> mDatas = new ArrayList<>();

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        if(binding == null){
            binding = DataBindingUtil.inflate(inflater,R.layout.fragment_my,container,false);
        }
        return binding.getRoot();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if(binding != null){
            meJumpAdapter = new MeJumpAdapter(mDatas);
            binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            binding.recyclerView.setAdapter(meJumpAdapter);
            binding.recyclerView.addItemDecoration(new MyJumpDecoration(getContext(),1,getResources().getColor(R.color.color_0E0F1A)));
            meJumpAdapter.setOnItemClickListener((adapter, view, position) -> {
                if(mDatas.get(position).getJumpName().equals(ChatActivity.class.getName())){
                    startActivity(new Intent(getContext(),ChatActivity.class).putExtra("id","echatkefu01"));
                }else if(mDatas.get(position).getJumpName().equals(AuthenticationUserActivity.class.getName())){
                    Intent intent = new Intent(getContext(),AuthenticationUserActivity.class);
                    if(authUserBean == null){
                        intent.putExtra("type",AuthenticationUserActivity.TYPE_SUBMIT);
                    }else if(authUserBean.getAuth_status() == 1){
                        intent.putExtra("type",AuthenticationUserActivity.TYPE_SUBMIT);
                    }else if(authUserBean.getAuth_status() == 3){
                        intent.putExtra("type",AuthenticationUserActivity.TYPE_ERRO);
                        intent.putExtra("reason",authUserBean.getReject_reason());
                    }else if(authUserBean.getAuth_status() == 2){
                        ToastUtils.toastMsg(getContext(),"当前用户已认证");
                        return;
                    }
                    startActivityForResult(intent,Contancts.REQUST_AUTH_USER);
                }else if(AuthenticationZhuboActivity.class.getName().equals(mDatas.get(position).getJumpName())){
                    if(UserHelper.getUser().getUser_role() == UserBean.TYPE_ANCHOR){
                        ToastUtils.toastMsg(getContext(),"已经是主播了");
                        return;
                    }
                    Intent intent = new Intent(getContext(),AuthenticationZhuboActivity.class);
                    startActivityForResult(intent,Contancts.REQUST_UPDATE_USET_INFO);
                }else {
                    RouterHelper.openActivity(getContext(), new Intent(), mDatas.get(position).getJumpName());
                }
            });
            binding.head.setOnClickListener(v -> startActivityForResult(new Intent(getContext(), PersonInfoActivity.class), Contancts.REQUST_UPDATE_USET_INFO));
            binding.llValue.setOnClickListener(v -> startActivityForResult(new Intent(getContext(), ValueActivity.class),Contancts.REQUST_UPDATE_USET_INFO));
            loadMenu();
            showView();
            getAuthUser();
            refreshUser();
        }

        findView(R.id.check_status).setOnClickListener(this);
    }


    /**
     * 根据用户信息加载菜单
     */
    private void loadMenu(){
        this.mDatas.addAll(MeHelper.getJumpBean(UserHelper.getUser()));
        this.meJumpAdapter.notifyDataSetChanged();
    }

    /**
     * 根据用户信息加载页面
     */
    @SuppressLint("SetTextI18n")
    private void showView(){
        /**
         * 加载用户头像和背景
         */
        ImageLoadUtils.loadBlurImage(getContext(),UserHelper.getUser().getAvatar(),binding.bg);
        ImageLoadUtils.loadImage(getContext(),UserHelper.getUser().getAvatar(),binding.head);
        binding.level.setText("LV."+(TextUtils.isEmpty(UserHelper.getUser().getLevel() )?"0":UserHelper.getUser().getLevel()));
        binding.sign.setText(String.format("个性签名:%s",UserHelper.getUser().getSign() == null?"":
                UserHelper.getUser().getSign()));

        binding.valueNumber.setText(String.format("%sE/min",UserHelper.getUser().getPrice() == null?"0":UserHelper.getUser().getPrice()));
        binding.rightValue.setText(UserHelper.getUser().getE_money()+"");
        binding.nickName.setText(UserHelper.getUser().getUsername() == null?"":UserHelper.getUser().getUsername());

        //根据认证显示V 以及主播价值，查看我的房间
        if(UserHelper.getUser().getUser_role() == UserBean.TYPE_ORIDINARY){
            //当前用户是普通用户
            binding.llValue.setVisibility(View.GONE);
            binding.seeMe.setVisibility(View.GONE);
            binding.llVip.setVisibility(View.GONE);
            binding.leftTitle.setText("关注");
            binding.leftNumber.setText(UserHelper.getUser().getFocus()+"");
            binding.llLike.setOnClickListener(v -> {
                startActivity(new Intent(getContext(),LikeActivity.class));
            });
            binding.zs.setVisibility(View.GONE);
            binding.llStatus.setVisibility(View.GONE);
            binding.llVip.setOnClickListener(v ->{});
        }else if(UserHelper.getUser().getUser_role() == UserBean.TYPE_FORMA){
            //当前用户是正式用户
            binding.llValue.setVisibility(View.GONE);
            binding.seeMe.setVisibility(View.GONE);
            binding.llVip.setVisibility(View.GONE);
            binding.zs.setVisibility(View.VISIBLE);
            binding.llStatus.setVisibility(View.GONE);
            binding.leftTitle.setText("关注");
            binding.leftNumber.setText(UserHelper.getUser().getFocus()+"");
            binding.llLike.setOnClickListener(v -> {
                startActivity(new Intent(getContext(),LikeActivity.class));
            });
            binding.llVip.setOnClickListener(v ->{});
        }else{
            binding.leftTitle.setText("粉丝");
            binding.leftNumber.setText(UserHelper.getUser().getFans()+"");
            //当前用户是主播
            binding.llLike.setOnClickListener(v -> {
                startActivity(new Intent(getContext(),MyFanseActivity.class));
            });
            binding.llValue.setVisibility(View.VISIBLE);
            binding.seeMe.setVisibility(View.VISIBLE);
            binding.zs.setVisibility(View.GONE);
            binding.llVip.setVisibility(View.VISIBLE);
            binding.llStatus.setVisibility(View.VISIBLE);
            binding.checkStatus.setOnClickListener(this);
            binding.llVip.setOnClickListener(v -> startActivity(new Intent(getContext(), AnchorHomeActivity.class).putExtra("extra_str_id",UserHelper.getUserId())));
            getStaus();
        }
    }

    private boolean isOnline;
    @Override
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.check_status:
//                findImageView(R.id.check_status).setImageResource(isOnline?R.drawable.kai:R.drawable.guan);
//                findImageView(R.id.iv_status).setImageResource(isOnline?R.mipmap.ic_in_line:R.mipmap.ic_out_line);
                sendStatus(isOnline?0:1);
                break;

            default:
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Contancts.REQUST_UPDATE_USET_INFO && resultCode == RESULT_OK){
//            refreshUser();
        }if(requestCode == Contancts.REQUST_AUTH_USER){
            getAuthUser();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshUser();
    }

    public void refreshUser(){
        String key = "9b4aaf?&&##664bdef@c3fc3efa9";
        new HttpUtilsRequst<Token>(getContext(),HttpUtilsRequst.retrofitClient.create(UserApi.class).getUserInfo(UserHelper.getToken(), MD5.Md5(System.currentTimeMillis()/1000+key).toLowerCase()),false)
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<UserBean>) userInfo -> {
                    UserHelper.save(userInfo);
                    MyApplication.getInstance().e_money = userInfo.getE_money();
                    showView();
                }).start();
    }

    /**
     * 用户认证记录
     */
    AuthUserBean authUserBean;
    /**
     * 获得认证记录
     */
    private void getAuthUser(){
        new HttpUtilsRequst<AuthUserBean>(getContext(),HttpUtilsRequst.retrofitClient.create(UserApi.class).getAuthResult(UserHelper.getToken()),false)
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<AuthUserBean>) authUserBean -> {
                    MyFragment.this.authUserBean = authUserBean;
                    //根据认证显示V 以及主播价值，查看我的房间
                    if(authUserBean == null || authUserBean.getAuth_status() == 1 || authUserBean.getAuth_status() == 3){
                        binding.zs.setVisibility(View.GONE);
                    }else{
                        binding.zs.setVisibility(View.VISIBLE);
                    }
                })
                .start();
    }


    /**
     * 獲取當前用戶狀態
     */
    private void getStaus(){
        new HttpUtilsRequst<UserStatus>(getContext(),HttpUtilsRequst.retrofitClient.create(UserApi.class).getAnchorStatusd(UserHelper.getUserId()),false)
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<UserStatus>) userStatuses -> {
                    if( null == userStatuses){
                        return;
                    }
                    if("1".equals(userStatuses.getStatus())){
                        isOnline = true;
                        binding.checkStatus.setImageResource(R.mipmap.kai);
                        binding.ivStatus.setImageResource(R.mipmap.ic_in_line);
                        //在綫
                    }else{
                        //不在綫
                        isOnline = false;
                        binding.checkStatus.setImageResource(R.mipmap.guan);
                        binding.ivStatus.setImageResource(R.mipmap.ic_out_line);
                    }
                })
                .setmOnRequstFaileListener((code, msg) -> {

                })
                .start();
    }


    /**
     * 設置用戶
     */
    private void sendStatus(int status){
//        SendStatusForm sendStatusForm = new SendStatusForm(UserHelper.getUserId(),String.valueOf(status));
        RequestBody username = RequestBody.create(MediaType.parse("multipart/form-data"),UserHelper.getUserId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),String.valueOf(status));
        new HttpUtilsRequst<List<UserStatus>>(getContext(),HttpUtilsRequst.retrofitClient.create(UserApi.class).
               sendAnchorSstatus(username,requestBody))
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<String>) s -> {
                    isOnline = !isOnline;
                    if(isOnline){
                        binding.checkStatus.setImageResource(R.mipmap.kai);
                        binding.ivStatus.setImageResource(R.mipmap.ic_in_line);
                        //在綫
                    }else{
                        //不在綫
                        binding.ivStatus.setImageResource(R.mipmap.ic_out_line);
                        binding.checkStatus.setImageResource(R.mipmap.guan);
                    }
                })
                .start();
    }
}
